import os
import subprocess
import glob


def shp2_postgres_sql(qgis_bin_path, shp_path, db_name):
    os.chdir(qgis_bin_path)
    shp_name = os.path.basename(shp_path).split(".")[0].split("_")[-1]

    # -nlt PROMOTE_TO_MULTI 如果导入数据是Polygon，则强制转换为MultiPolygon。由于创建的目标数据要求几何为MultiPolygon，如果Polygon不转为MultiPolygon，则无法导入
    cmd_str = f'''ogr2ogr -f "PostgreSQL" PG:"host=127.0.0.1 port=5432 dbname={db_name} user=postgres password=egova schemas=public" "{shp_path}" \
-lco GEOMETRY_NAME=geom \
-lco FID=fid \
--config SHAPE_ENCODING "GBK" \
-nlt PROMOTE_TO_MULTI \
-lco SPATIAL_INDEX=GIST \
-nln {shp_name} \
-overwrite \
-oo TIMESTAMP_FORMAT="YYYY-MM-DD HH24:MI:SS"'''
    print(cmd_str)
    subprocess.run(cmd_str, shell=True)


def multi_import(qgis_bin_path, shp_dir, db_name):
    for path in glob.glob(shp_dir + "/*.shp"):
        shp2_postgres_sql(qgis_bin_path, path, db_name)


if __name__ == '__main__':
    ogr2ogr_dir = r"D:\software\QGIS3.40.7\bin"
    shp_dir = r"E:\现场数据\重庆管线\chongqing1227"
    db_name = "chongqing"
    os.environ['PRO_LIB'] = ogr2ogr_dir
    print(os.environ.get('PRO_LIB'))
    multi_import(ogr2ogr_dir, shp_dir, db_name)
